package org.convallaria.infrastruct.rg.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.convallaria.infrastruct.rg.service.ConfigManagementService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置管理控制器
 * 提供Nacos配置管理的REST API
 * 只有在ConfigManagementService可用时才启用
 * 
 * @author gjh
 * @since 2025-01-27
 */
@Slf4j
@RestController
@RequestMapping("/api/registry/config")
@RequiredArgsConstructor
@ConditionalOnBean(ConfigManagementService.class)
public class ConfigManagementController {
    
    private final ConfigManagementService configManagementService;
    
    /**
     * 获取配置
     * 
     * @param dataId 配置ID
     * @param group 配置组
     * @return 配置内容
     */
    @GetMapping("/{dataId}")
    public Map<String, Object> getConfig(
            @PathVariable String dataId,
            @RequestParam(defaultValue = "DEFAULT_GROUP") String group) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            String content = configManagementService.getConfig(dataId, group);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("content", content);
            result.put("success", true);
            result.put("timestamp", System.currentTimeMillis());
            
            log.info("获取配置成功: dataId={}, group={}", dataId, group);
        } catch (Exception e) {
            log.error("获取配置失败: dataId={}, group={}", dataId, group, e);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
    
    /**
     * 获取配置（带默认值）
     * 
     * @param dataId 配置ID
     * @param group 配置组
     * @param defaultValue 默认值
     * @return 配置内容
     */
    @GetMapping("/{dataId}/with-default")
    public Map<String, Object> getConfigWithDefault(
            @PathVariable String dataId,
            @RequestParam(defaultValue = "DEFAULT_GROUP") String group,
            @RequestParam(defaultValue = "") String defaultValue) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            String content = configManagementService.getConfig(dataId, group, defaultValue);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("content", content);
            result.put("defaultValue", defaultValue);
            result.put("success", true);
            result.put("timestamp", System.currentTimeMillis());
            
            log.info("获取配置成功（带默认值）: dataId={}, group={}, defaultValue={}", dataId, group, defaultValue);
        } catch (Exception e) {
            log.error("获取配置失败: dataId={}, group={}, defaultValue={}", dataId, group, defaultValue, e);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
    
    /**
     * 发布配置
     * 
     * @param dataId 配置ID
     * @param group 配置组
     * @param content 配置内容
     * @return 发布结果
     */
    @PostMapping("/{dataId}")
    public Map<String, Object> publishConfig(
            @PathVariable String dataId,
            @RequestParam(defaultValue = "DEFAULT_GROUP") String group,
            @RequestBody String content) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = configManagementService.publishConfig(dataId, group, content);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", success);
            result.put("timestamp", System.currentTimeMillis());
            
            if (success) {
                log.info("发布配置成功: dataId={}, group={}", dataId, group);
            } else {
                log.warn("发布配置失败: dataId={}, group={}", dataId, group);
            }
        } catch (Exception e) {
            log.error("发布配置异常: dataId={}, group={}", dataId, group, e);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
    
    /**
     * 删除配置
     * 
     * @param dataId 配置ID
     * @param group 配置组
     * @return 删除结果
     */
    @DeleteMapping("/{dataId}")
    public Map<String, Object> removeConfig(
            @PathVariable String dataId,
            @RequestParam(defaultValue = "DEFAULT_GROUP") String group) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = configManagementService.removeConfig(dataId, group);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", success);
            result.put("timestamp", System.currentTimeMillis());
            
            if (success) {
                log.info("删除配置成功: dataId={}, group={}", dataId, group);
            } else {
                log.warn("删除配置失败: dataId={}, group={}", dataId, group);
            }
        } catch (Exception e) {
            log.error("删除配置异常: dataId={}, group={}", dataId, group, e);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
    
    /**
     * 检查配置是否存在
     * 
     * @param dataId 配置ID
     * @param group 配置组
     * @return 检查结果
     */
    @GetMapping("/{dataId}/exists")
    public Map<String, Object> configExists(
            @PathVariable String dataId,
            @RequestParam(defaultValue = "DEFAULT_GROUP") String group) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            boolean exists = configManagementService.configExists(dataId, group);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("exists", exists);
            result.put("success", true);
            result.put("timestamp", System.currentTimeMillis());
            
            log.debug("检查配置是否存在: dataId={}, group={}, exists={}", dataId, group, exists);
        } catch (Exception e) {
            log.error("检查配置是否存在失败: dataId={}, group={}", dataId, group, e);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
    
    /**
     * 获取配置信息
     * 
     * @param dataId 配置ID
     * @param group 配置组
     * @return 配置信息
     */
    @GetMapping("/{dataId}/info")
    public Map<String, Object> getConfigInfo(
            @PathVariable String dataId,
            @RequestParam(defaultValue = "DEFAULT_GROUP") String group) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            ConfigManagementService.ConfigInfo configInfo = configManagementService.getConfigInfo(dataId, group);
            if (configInfo != null) {
                result.put("dataId", configInfo.getDataId());
                result.put("group", configInfo.getGroup());
                result.put("content", configInfo.getContent());
                result.put("exists", configInfo.isExists());
                result.put("timestamp", configInfo.getTimestamp());
                result.put("success", true);
                
                log.debug("获取配置信息成功: dataId={}, group={}", dataId, group);
            } else {
                result.put("dataId", dataId);
                result.put("group", group);
                result.put("exists", false);
                result.put("success", true);
                result.put("timestamp", System.currentTimeMillis());
                
                log.debug("配置不存在: dataId={}, group={}", dataId, group);
            }
        } catch (Exception e) {
            log.error("获取配置信息失败: dataId={}, group={}", dataId, group, e);
            result.put("dataId", dataId);
            result.put("group", group);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
}
